package com.smart.community.commons.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * Redis锁工具类
 * 
 * @author Wu.Liang
 */
@Slf4j
@Component
public class RedisLockUtil {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private static final String LOCK_PREFIX = "lock:";
    private static final long DEFAULT_TIMEOUT = 30000; // 30秒

    /**
     * 尝试获取锁
     */
    public boolean tryLock(String key, long timeout, TimeUnit unit) {
        String lockKey = LOCK_PREFIX + key;
        try {
            Boolean result = redisTemplate.opsForValue().setIfAbsent(lockKey, "1", timeout, unit);
            return result != null && result;
        } catch (Exception e) {
            log.error("获取锁失败: {}", key, e);
            return false;
        }
    }

    /**
     * 释放锁
     */
    public boolean unlock(String key) {
        String lockKey = LOCK_PREFIX + key;
        try {
            Boolean result = redisTemplate.delete(lockKey);
            return result != null && result;
        } catch (Exception e) {
            log.error("释放锁失败: {}", key, e);
            return false;
        }
    }
}
